<?php

require_once 'Vega/Db/Abstract.php';

class Vega_Db_Mysql extends Vega_Db_Abstract
{
    protected $_functions = array(
        'fetch_array'   => 'mysql_fetch_array',
        'query'         => 'mysql_query',
        'connect'       => 'mysql_connect',
        'pconnect'      => 'mysql_pconnect',
        'insert_id'     => 'mysql_insert_id',
        'select_db'     => 'mysql_select_db',
        'escape_string' => 'mysql_escape_string',
        'error'         => 'mysql_error',
        'num_rows'      => 'mysql_num_rows',
        'free_result'   => 'mysql_free_result',
        'affected_rows' => 'mysql_affected_rows',
    );

    /**
     * Use mysql unbuffered query or not.
     * When use unbuffered query, numRows does not work.
     *
     * @param boolean $use
     */
    public function useUnbufferedQuery($use = true)
    {
        if ($use)
        {
            $this->_functions['query'] = 'mysql_unbuffered_query';
        }
        else
        {
            $this->_functions['query'] = 'mysql_query';
        }
        return $this;
    }

    public function escape($string)
    {
        $this->connect('master');
        return mysql_real_escape_string($string, $this->_conns['master']);
    }
    
    public function fieldQuote($field)
    {
        return "`$field`";
    }
    
    /**
     * Make limited query
     * Borrowed from Zend Framework
     * 
     * @param string $sql
     * @param integer $limit
     * @param integer $offset
     * @return string
     */
    public function limit($sql, $limit, $offset)
    {
        $count = intval($count);
        if ($count <= 0) {
            
            require_once 'Vega/Db/Exception.php';
            throw new Vega_Db_Exception("LIMIT argument count=$count is not valid");
        }

        $offset = intval($offset);
        if ($offset < 0) {
            
            require_once 'Vega/Db/Exception.php';
            throw new Vega_Db_Exception("LIMIT argument offset=$offset is not valid");
        }
        
        $sql .= " LIMIT $count";
        if ($offset > 0) {
            $sql .= " OFFSET $offset";
        }
        return $sql;
    }
    
    /**
     * Begins a transaction
     *
     * @return mixed
     */
    public function beginTransaction()
    {
        return $this->queryWrite('START TRANSACTION');
    }
    
    /**
     * Rolls back a transaction
     *
     * @return mixed
     */
    public function rollBack()
    {
        return $this->queryWrite('ROLLBACK');
    }
    
    /**
     * Commits
     *
     * @return mixed
     */
    public function commit()
    {
        return $this->queryWrite('COMMIT');
    }
}
